<template>
  <div class="page-main">
    <query-page
      ref="pageRef"
      v-model:selectedKeys="selectedKeys"
      :form-component-config="formComponentConfig"
      :form-render-config="formRenderConfig"
      :form-render-keys="formRenderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="renderData"
      title="采购计划选商结果查询"
      :total="total"
      row-selection-type="checkbox"
      @query-data="getData"
    >
      <template #top-container>
        <p-tabs
          v-model:value="activeTab"
          :is-show-num="true"
          :tab-list="tabList"
        ></p-tabs>
      </template>
      <template #container-side>
        <a-tooltip :content="btnContent" background-color="#165DFF">
          <a-button
            v-permission="['procurement:supplier-chose-result:fallback']"
            :disabled="selectedKeys.length === 0"
            @click="returnClick"
            >退回</a-button
          >
        </a-tooltip>
      </template>
      <template #attachment="{ record }">
        <a-popover
          title="查看附件"
          trigger="click"
          :content-style="styleUpload"
        >
          <a-button type="text" @click="handleAttachment(record)"
            >查看附件</a-button
          >
          <template #content>
            <div v-if="attachmentList.length === 0">暂无附件信息查看</div>
            <div
              v-for="(item, index) in attachmentList"
              :key="index"
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <p style="width: 150px">{{ item.fileName }}</p>
              <div>
                <span
                  style="margin: 0 10px; color: #165dff; cursor: pointer"
                  @click="handleDown(item)"
                  >下载</span
                >
                >
              </div>
            </div>
          </template>
        </a-popover>
      </template>
      <template #operate="{ record }">
        <a-button
          v-permission="['procurement:supplier-chose-result:updateResult']"
          type="text"
          @click="updateClick(record)"
          >更新采购价格</a-button
        >
      </template>
    </query-page>
    <contentModel
      v-if="visible"
      :title="'更新采购价格'"
      @close="visible = false"
    >
      <template #footer>
        <a-space>
          <a-button type="primary" @click="putSheet">确定</a-button>
          <a-button @click="visible = false">取消</a-button>
        </a-space>
      </template>
      <a-spin :loading="modalLoading" style="width: 100%">
        <a-form
          :loading="true"
          :model="formSheet"
          layout="vertical"
          class="edit-form"
        >
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item field="inputType" label="录入类型">
                <dictSelect
                  v-model="formSheet.inputType"
                  placeholder="请输入录入类型"
                  dict-type="inputType"
                  allow-clear
                  @change="formChange"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="pmsInvPrice" label="不含税单价（库存）">
                <a-input
                  v-model="formSheet.pmsInvPrice"
                  placeholder="请输入不含税单价（库存）"
                  disabled
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="mdsUintRate" label="转换系数">
                <a-input v-model="formSheet.mdsUintRate" allow-clear disabled />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="exTaxPrice" label="不含税单价（采购）">
                <a-input
                  v-model="formSheet.exTaxPrice"
                  placeholder="请输入不含税单价（采购）"
                  :disabled="formSheet.inputType === '1'"
                  allow-clear
                  @change="formChange"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="pmsBalancePrice" label="不含税结算单价">
                <a-input
                  v-model="formSheet.pmsBalancePrice"
                  placeholder="请输入不含税结算单价"
                  :disabled="formSheet.inputType === '1'"
                  allow-clear
                  @change="formChange"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="taxRate" label="税率（%）">
                <dict-select
                  v-model="formSheet.taxRateCode"
                  style="width: 200px"
                  allow-clear
                  dict-type="taxRate"
                  placeholder="请输入税率（%）"
                  @change="formChange"
                ></dict-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="taxPrice" label="含税单价">
                <a-input
                  v-model="formSheet.taxPrice"
                  placeholder="请输入含税单价"
                  :disabled="formSheet.inputType !== '1'"
                  allow-clear
                  @change="formChange"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="pmsInvTaxPrice" label="含税结算单价">
                <a-input
                  v-model="formSheet.pmsInvTaxPrice"
                  placeholder="请输入含税结算单价"
                  :disabled="formSheet.inputType !== '1'"
                  allow-clear
                  @change="formChange"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="pmsEstimatePrice" label="预估价">
                <a-input
                  v-model="formSheet.pmsEstimatePrice"
                  placeholder="请输入预估价"
                  allow-clear
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </contentModel>
  </div>
</template>

<script lang="ts" setup>
  import {
    ref,
    onMounted,
    watch,
    defineAsyncComponent,
    CSSProperties,
    nextTick,
  } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import queryPage from '@/common/components/query-page/index.vue';
  import promiseModal from '@/common/utils/modal-promise';
  import {
    supplierList,
    updateResult,
    fallback,
    execCalculate,
  } from '@/api/supplier/parity-sheet';
  import lodash from 'lodash';
  import { getPlanFileListByplanListNo } from '@/api/supplier/selective-quotient';
  import dictSelect from '@/common/components/dict-select/index.vue';
  // import nameTitle from './components/name-title.vue';
  import {
    formRenderConfig,
    formComponentConfig,
  } from './components/formComp/baseFormConfig';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from './components/tableComp/baseTableConfig';
  import { baseRenderKeys } from './components/baseDatapurchase';
  // import { getBtnList } from './components/baseBtnpurchaseplan';
  // import { getRowBtnList } from './components/rowBaseBtn';
  import PTabs from './components/p-tabs.vue';

  const btnContent = `退回根据选商策略不同 \n 1、单一来源采购、比选采购、竞争性谈判采购、招标等在选商方式确认中查看;\n2、询价采购在比价单提交中查看;\n3、不付费在采购计划接收中查看。`;
  const contentModel = defineAsyncComponent(
    () => import('@/common/components/content-model/index.vue')
  );
  const modalLoading = ref(false);
  const selectedKeys = ref([]);
  const formSheet = ref<any>({});
  const attachmentList = ref<any>([]);
  const styleUpload =
    'max-height:300px;overflow: auto;' as unknown as CSSProperties;
  const visible = ref(false);
  const activeTab = ref('2');
  const activeRadio = ref('');
  const pageRef = ref();
  const isLoading = ref(true);
  const renderData = ref<any[]>([]);
  // ( 1标准件 2 成品 3原材料 4 零组件 5锻铸件)
  const tabList = ref([
    { label: '成品', id: '2' },
    { label: '原材料', id: '3' },
    { label: '标准件', id: '1' },
    { label: '零组件', id: '4' },
    { label: '锻铸件', id: '5' },
  ]);
  const total = ref(0);
  // 渲染检索项
  const formRenderKeys = ref<any[]>([]);
  // 当前表格要渲染哪些值
  const tableRenderKeys = ref<any[]>([]);
  tableRenderKeys.value = baseRenderKeys.finishedProduct.newTableRenderKeys;

  const getData = async (queryInfo: any) => {
    console.log(queryInfo);
    isLoading.value = true;
    try {
      const res: any = await supplierList({
        ...queryInfo,
        mdsItemType: activeTab.value,
      });
      if (res.code === 200) {
        renderData.value = res.data.records;
        total.value = res.data.total;
        console.log(res);
      }
    } catch (err: any) {
      console.log(err);
    }
    isLoading.value = false;
  };
  const handleDown = (val: any) => {
    window.open(val.url);
  };
  const handleAttachment = async (record: any) => {
    const { data } = await getPlanFileListByplanListNo(record.planListNo);
    attachmentList.value = data;
    console.log(data);
  };
  const putSheet = async () => {
    // const pmsPlanSupplierIds = selectedKeys.value.map((id) => {
    //   return renderData.value.find((item) => item.id === id).pmsPlanSupplierId;
    // });
    const pmsPlanSupplierIds = [formSheet.value.pmsPlanSupplierId];
    const params = {
      pmsPlanSupplierIds,
      ...formSheet.value,
    };
    try {
      const res: any = await updateResult(params);
      if (res.code === 200) {
        Message.success('更新成功');
        visible.value = false;
        getData(pageRef.value.getStatus());
        selectedKeys.value = [];
      }
    } catch (err: any) {
      console.log(err);
    }
  };
  const returnClick = async () => {
    try {
      await promiseModal.confirm({
        title: '回退',
        content: '您确定要回退当前所选的数据？',
        modalStyle: { wordBreak: 'break-all' },
      });
    } catch (e: any) {
      return;
    }
    const planListNos = selectedKeys.value.map((id) => {
      return renderData.value.find((item) => item.id === id).planListNo;
    });
    const params = {
      planListNos,
    };
    try {
      const res: any = await fallback(params);
      if (res.code === 200) {
        Message.success('退回成功');
        visible.value = false;
        getData(pageRef.value.getStatus());
        selectedKeys.value = [];
      }
    } catch (err: any) {
      console.log(err);
    }
  };
  const initData = () => {
    selectedKeys.value = [];
    const cfg: any = {
      1: 'standardPart',
      2: 'finishedProduct',
      3: 'rawMaterial',
      4: 'zeroCom',
      5: 'forgingAndCasting',
    };
    const renderKey = cfg[activeTab.value];
    formRenderKeys.value =
      lodash.get(baseRenderKeys, `${renderKey}.formRenderKeys`) || [];
    tableRenderKeys.value =
      lodash.get(baseRenderKeys, `${renderKey}.newTableRenderKeys`) || [];
  };
  const updateClick = (form: any = {}) => {
    formSheet.value = { ...form };
    visible.value = true;
  };
  const formChange = async () => {
    modalLoading.value = true;
    try {
      const res: any = await execCalculate(formSheet.value);
      if (res.code === 200) {
        const result = res.data;
        // Object.keys(result).forEach((key) => {
        //   if (result[key] === '') delete result[key];
        // });
        formSheet.value = Object.assign(formSheet.value, result);
      }
    } catch {
      console.log('计算错误');
    } finally {
      modalLoading.value = false;
    }
  };
  watch(activeTab, () => {
    // console.log(newval, oldval, 'activeTab');
    // activeRadio.value = '1';
    initData();
    nextTick(() => {
      getData(pageRef.value.getStatus());
    });
  });
  watch(activeRadio, () => {
    // console.log(newval, oldval, 'activeRadio');
    initData();
  });
  onMounted(() => {
    initData();
  });
</script>

<style lang="less" scoped>
  .outbox {
    // width: 100%;
    // height: 100%;
    margin: 16px;
  }

  .supbox {
    // margin: 8px;
    padding: 0 24px 16px;
    background-color: white;
    border-radius: 6px;
  }

  .radio-ara {
    display: flex;
    justify-content: space-between;
    width: 17.5%;
  }

  .edit-form {
    ::v-deep .arco-form-item {
      background: #fff;

      &:focus-within {
        border-color: #165dff;
      }

      .arco-form-item-wrapper-col {
        border: 1px solid #d9dee7;
        border-radius: 3px;
      }

      .arco-picker-size-medium {
        width: 100%;
      }

      .arco-select-view-size-medium {
        width: 100% !important;
      }

      .arco-input-wrapper,
      .arco-picker,
      .arco-select-view-single {
        padding: 0 8px;
        background-color: transparent;
        border-color: transparent;
      }
    }
  }
</style>
